package com.sneakxy.mybase4j.platform.controller;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sneakxy.mybase4j.base.bean.ValidAdd;
import com.sneakxy.mybase4j.base.bean.ValidEdit;
import com.sneakxy.mybase4j.base.controller.BaseController;
import com.sneakxy.mybase4j.platform.beans.Menu;
import com.sneakxy.mybase4j.platform.service.IMenuService;
import com.sneakxy.mybase4j.util.BeanHelper;
import com.sneakxy.mybase4j.util.Response;

/**
 * 菜单管理
 * @author 潜行的青衣
 * @see
 */
@RestController
@RequestMapping("/api/menu/")
public class MenuController extends BaseController {

	@Resource
	private IMenuService menuService;
	
	@RequiresPermissions("sys:menu:manager")
	@RequestMapping("tree")
	public Response tree(String type) {
		Map<String, Object> result = new LinkedHashMap<String, Object>();
		List<Menu> list = this.menuService.findTreeByType(StringUtils.trimToEmpty(type));
		result.put("id", type);
		result.put("i18n", "sys.menu.manager");
		result.put("open", true);
		result.put("children", list);
		return new Response(result);
	}
	
	@RequiresPermissions("sys:menu:manager:add")
	@RequestMapping("add")
	public Response add(@Validated(ValidAdd.class) Menu menu, BindingResult result) {
		if(result.hasErrors()) {
			return this.getFieldErrorsResponse(result);
		}
		
		//去空格
		BeanHelper.trimToNull(menu);
		
		menu = this.menuService.save(menu);
		return new Response(true, menu);
	}
	
	@RequiresPermissions("sys:menu:manager:edit")
	@RequestMapping("edit")
	public Response edit(@Validated(ValidEdit.class) Menu menu, BindingResult result) {
		if(result.hasErrors()) {
			return this.getFieldErrorsResponse(result);
		}
		
		//去空格
		BeanHelper.trimToNull(menu);
		
		Menu old = this.menuService.findOne(menu.getId());
		menu.setCreatetime(old.getCreatetime());
		menu.setType(old.getType());
		
		menu = this.menuService.save(menu);
		return new Response(true, menu);
	}
	
	@RequiresPermissions("sys:menu:manager:remove")
	@RequestMapping("remove")
	public Response remove(String id) {
		String menuId = StringUtils.trimToEmpty(id);
		if(StringUtils.isNotBlank(menuId) && !this.menuService.hasChildren(id)) {
			this.menuService.delete(menuId);
			return new Response(true);
		}
		return new Response(false, 1);
	}
}
